package com.example.tellwin.question.act;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.tellwin.CallService;
import com.example.tellwin.MainApplication;
import com.example.tellwin.R;
import com.example.tellwin.base.CpBaseActivty;
import com.example.tellwin.base.DaggerRxComponent;
import com.example.tellwin.common.Common;
import com.example.tellwin.event.CallEvent;
import com.example.tellwin.event.IMEventBean;
import com.example.tellwin.event.OrderDetailEvent;
import com.example.tellwin.event.OrderListEvent;
import com.example.tellwin.mine.bean.OrderDetailBean;
import com.example.tellwin.model.TRTCCalling;
import com.example.tellwin.model.impl.TRTCCallingImpl;
import com.example.tellwin.question.contract.AnswerContract;
import com.example.tellwin.question.presenter.AnswerPresenter;
import com.example.tellwin.tic.TICManager;
import com.example.tellwin.utils.CommonUtils;
import com.example.tellwin.utils.GlideUtils;
import com.example.tellwin.utils.ToastUtil;
import com.example.tellwin.view.BlurTransformation;
import com.example.tellwin.view.ConfirmDialog;
import com.google.gson.Gson;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.tencent.rtmp.ui.TXCloudVideoView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.example.tellwin.model.TRTCCalling.TYPE_AUDIO_CALL;
import static com.example.tellwin.model.TRTCCalling.TYPE_VIDEO_CALL;

public class AnswerActivity extends CpBaseActivty implements AnswerContract.View {

    @BindView(R.id.bg_iv)
    ImageView bgIv;
    @BindView(R.id.teacher_head_iv)
    ImageView headIv;
    @BindView(R.id.teacher_name_tv)
    TextView teacherNameTv;
    @BindView(R.id.voice_answer_tv)
    TextView voiceAnswerTv;
    @BindView(R.id.video_answer_tv)
    TextView videoAnswerTv;
    @BindView(R.id.white_board_answer_tv)
    TextView whiteBoardAnswerTv;
    @BindView(R.id.answer_over_btn)
    TextView answerOverBtn;
    @BindView(R.id.answer_type_ll)
    LinearLayout answerTypeLl;
    @BindView(R.id.answer_tv)
    TextView answerTv;
    @BindView(R.id.cancel_tv)
    TextView cancelTv;
    @BindView(R.id.video_ll)
    LinearLayout videoLl;
    @BindView(R.id.calling_cancel_btn)
    TextView callingCancelBtn;
    @BindView(R.id.trtc_tc_cloud_view)
    TXCloudVideoView txCloudVideoView;
    @BindView(R.id.small_trtc_tc_cloud_view)
    TXCloudVideoView smallTxCloudVideoView;
    @BindView(R.id.teacher_head_ll)
    RelativeLayout headRl;

    private Runnable mTimeRunnable;
    private int mTimeCount;
    private Handler mTimeHandler;
    private HandlerThread mTimeHandlerThread;

    @Inject
    AnswerPresenter mPresenter;

    private OrderDetailBean orderDetailBean;

    private String orderId;//普通用户接到通话后，解答人通过im发送过来订单id
    private String answerUserId;//解答人用户id
    int answerType;

    int classId = 100;

    TRTCCalling sCall;
    boolean isCalling;

    MediaPlayer mediaPlayer;

    Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1001:
                    mediaPlayer.start();
                    break;
                case 1002:
                    AnswerActivity.this.finish();
                    EventBus.getDefault().post(new OrderDetailEvent());
                    EventBus.getDefault().post(new OrderListEvent());
                    break;
            }
        }
    };

    V2TIMValueCallback<V2TIMMessage> callback = new V2TIMValueCallback<V2TIMMessage>() {
        @Override
        public void onError(int i, String s) {
            if (MainApplication.Identity.equals(Common.ANSWER)) {
                LogUtils.e("订单信息发送失败:" + i + "-" + s);
                ToastUtil.show(AnswerActivity.this, "订单信息发送失败:" + i + "-" + s);
            } else {
                LogUtils.e("解答方式发送失败:" + i + "-" + s);
                ToastUtil.show(AnswerActivity.this, "解答方式发送失败:" + i + "-" + s);
                videoLl.setVisibility(View.GONE);
            }
            //  V2TIMManager.getInstance().sendC2CTextMessage(orderDetailBean.getOrderId(), orderDetailBean.getUserId(), callback);
        }

        @Override
        public void onSuccess(V2TIMMessage v2TIMMessage) {
            if (answerType == 3) {
                Intent intent = new Intent(AnswerActivity.this, WriteBroadActivity.class);
                intent.putExtra(Common.ORDER_ID, orderId);
                intent.putExtra(Common.ClassId, classId);
                intent.putExtra(Common.USER_ID, answerUserId);
                startActivity(intent);
                finish();
            }
            if (MainApplication.Identity.equals(Common.ANSWER)) {
                LogUtils.e("订单信息发送成功");
            } else {
                LogUtils.e("解答方式发送成功");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_answer);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        LogUtils.e("AnswerActivity");
        initViews();
        initEvents();
        initDatas();
    }

    @Override
    protected void initViews() {
        DaggerRxComponent.builder()
                .baseAppComponent(MainApplication.getAppComponent())
                .build()
                .inject(this);
        mPresenter.attachView(this);
        sCall = TRTCCallingImpl.sharedInstance(this);


        mTimeHandlerThread = new HandlerThread("time-count-thread");
        mTimeHandlerThread.start();
        mTimeHandler = new Handler(mTimeHandlerThread.getLooper());

        mediaPlayer = new MediaPlayer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                AssetFileDescriptor file = null;
                AssetManager assetManager = AnswerActivity.this.getAssets();
                try {
                    file = assetManager.openFd("5363.mp3");
                    mediaPlayer.setDataSource(file.getFileDescriptor(),
                            file.getStartOffset(), file.getLength());
                    mediaPlayer.prepare();
                    mediaPlayer.seekTo(0);
                    file.close();
                    //assetManager.close();
                    uiHandler.sendEmptyMessage(1001);
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e(e);
                }
            }
        }).start();

    }

    @Override
    protected void initEvents() {
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //  CommonUtils.openAssestsMp3(AnswerActivity.this , mediaPlayer);
                mediaPlayer.start();
            }
        });
    }

    @Override
    protected void initDatas() {
        if (MainApplication.Identity == Common.ANSWER) {
            orderDetailBean = (OrderDetailBean) getIntent().getSerializableExtra(Common.ORDER);
            if (orderDetailBean == null) {
                finish();
                return;
            }
            // GlideUtils.loadHeadImage(this, orderDetailBean.getHeadPic(), headIv);
            mPresenter.userHeadPic(orderDetailBean.getUserId());
            sCall.call(orderDetailBean.getUserId(), TYPE_AUDIO_CALL);
            answerTypeLl.setVisibility(View.GONE);
            videoLl.setVisibility(View.GONE);
            callingCancelBtn.setVisibility(View.VISIBLE);
            answerOverBtn.setVisibility(View.GONE);
        } else {
            int type = getIntent().getIntExtra(Common.TYPE, 0);
            answerUserId = getIntent().getStringExtra(Common.USER_ID);
            if (type == Common.CALL_REMINDER) {
                answerTypeLl.setVisibility(View.GONE);
                videoLl.setVisibility(View.VISIBLE);
                callingCancelBtn.setVisibility(View.GONE);
                answerOverBtn.setVisibility(View.GONE);
                if (answerUserId == null) {
                    ToastUtil.show(this, "来电用户为空！");
                    finish();
                    return;
                }
                mPresenter.userHeadPic(answerUserId);
            }
        }
        // mediaPlayer.start();
    }

    @OnClick({R.id.voice_answer_tv, R.id.video_answer_tv, R.id.white_board_answer_tv, R.id.answer_over_btn, R.id.answer_tv, R.id.cancel_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.voice_answer_tv:
                mPresenter.selectAnswerType(orderId, 1);
                break;
            case R.id.video_answer_tv:
                mPresenter.selectAnswerType(orderId, 2);
                break;
            case R.id.white_board_answer_tv:
                mPresenter.selectAnswerType(orderId, 3);
                break;
            case R.id.answer_over_btn:
                if (MainApplication.Identity.equals(Common.NORMAL)) {
                    ConfirmDialog confirmDialog = new ConfirmDialog(AnswerActivity.this, "您的问题是否已解答？", new ConfirmDialog.OnConfrimClickListener() {
                        @Override
                        public void onConfrimClick() {
                            int callDuration = 0;
                            LogUtils.e(mTimeCount);
                            if (mTimeCount <= 60) {
                                callDuration = 1;
                            } else {
                                callDuration = mTimeCount % 60 == 0 ? mTimeCount / 60 : (mTimeCount / 60) + 1;
                            }
                            LogUtils.e(callDuration);
                            mPresenter.answerSuccess(orderId, "", callDuration + "");
                            //  finish();
                        }
                    });
                    confirmDialog.show();
                } else {
                    ConfirmDialog confirmDialog = new ConfirmDialog(AnswerActivity.this, "是否已解答完毕？", new ConfirmDialog.OnConfrimClickListener() {
                        @Override
                        public void onConfrimClick() {
                            int callDuration = 0;
                            LogUtils.e(mTimeCount);
                            if (mTimeCount <= 60) {
                                callDuration = 1;
                            } else {
                                callDuration = mTimeCount % 60 == 0 ? mTimeCount / 60 : (mTimeCount / 60) + 1;
                            }
                            LogUtils.e(callDuration);
                            mPresenter.answerSuccess(orderDetailBean.getOrderId(), "", callDuration + "");
                        }
                    });
                    confirmDialog.show();
                }

                break;
            case R.id.answer_tv://接听来电
                if (sCall == null) {
                    finish();
                    return;
                }
                sCall.accept();
            /*    isCalling = true;
                videoLl.setVisibility(View.GONE);
                answerOverBtn.setVisibility(View.VISIBLE);*/
                break;
            case R.id.cancel_tv://拒绝来电
                if (!TextUtils.isEmpty(orderId)) {
                    mPresenter.cancelOrder(orderId);
                } else {
                    cancelOrderSuccess();
                }
                break;
            case R.id.calling_cancel_btn://拨打电话中取消
                mPresenter.cancelOrder(orderDetailBean.getOrderId());
                break;
        }
    }

    @Override
    public void selectAnswerTypeResult(int type) {
        answerType = type;
        videoLl.setVisibility(View.GONE);
        sCall.hangup();
        if (type == 1) {
            answerTypeLl.setVisibility(View.GONE);
            videoLl.setVisibility(View.GONE);
            callingCancelBtn.setVisibility(View.GONE);
            answerOverBtn.setVisibility(View.GONE);
            sCall.call(answerUserId, TYPE_AUDIO_CALL);//重新拨打电话给老师
        } else if (type == 2) {
            answerTypeLl.setVisibility(View.GONE);
            videoLl.setVisibility(View.GONE);
            callingCancelBtn.setVisibility(View.GONE);
            answerOverBtn.setVisibility(View.GONE);
            sCall.call(answerUserId, TYPE_VIDEO_CALL);//重新发起视频通话给老师。
            headRl.setVisibility(View.GONE);
            smallTxCloudVideoView.setVisibility(View.VISIBLE);
            sCall.setMicMute(false);
            sCall.setHandsFree(true);
            sCall.openCamera(true, smallTxCloudVideoView);
        } else {//白板
            TICManager ticManager = MainApplication.getTICManager();
            final int scence = TICManager.TICClassScene.TIC_CLASS_SCENE_VIDEO_CALL; //如果使用大房间，请使用 TIC_CLASS_SCENE_LIVE
            LogUtils.e(classId);
            ticManager.destroyClassroom(classId, null);
            ticManager.createClassroom(classId, scence, new TICManager.TICCallback() {
                @Override
                public void onSuccess(Object data) {
                    IMEventBean imEventBean = new IMEventBean();
                    imEventBean.type = Common.Join_Room_Event;
                    imEventBean.classId = classId;
                    imEventBean.orderId = orderId;
                    V2TIMManager.getInstance().sendC2CTextMessage(new Gson().toJson(imEventBean), answerUserId, callback);
                }

                @Override
                public void onError(String module, int errCode, String errMsg) {
                    if (errCode == 10021) {
                        LogUtils.e("该课堂已被他人创建，请\"加入课堂\"");
                    } else if (errCode == 10025) {
                        LogUtils.e("该课堂已创建，请\"加入课堂\"");
                        IMEventBean imEventBean = new IMEventBean();
                        imEventBean.type = Common.Join_Room_Event;
                        imEventBean.classId = classId;
                        imEventBean.orderId = orderId;
                        V2TIMManager.getInstance().sendC2CTextMessage(new Gson().toJson(imEventBean), answerUserId, callback);
                    } else {
                        LogUtils.e("创建课堂失败, 房间号：" + classId + " err:" + errCode + " msg:" + errMsg);
                    }
                }
            });

        }
    }

    @Override
    public void userHeadPic(String headUrl, String name) {
        if (TextUtils.isEmpty(headUrl)) {
            int icon = Common.ANSWER.equals(MainApplication.Identity) ? R.mipmap.student_icon : R.mipmap.teacher_icon;
            GlideUtils.loadHeadImage(this, icon, headIv);
            Glide.with(this).load(icon).
                    apply(RequestOptions.bitmapTransform(new BlurTransformation(this, 23, 4))).into(bgIv);
        } else {
            GlideUtils.loadHeadImage(this, headUrl, headIv);
            Glide.with(this).load(headUrl).
                    apply(RequestOptions.bitmapTransform(new BlurTransformation(this, 23, 4))).into(bgIv);
        }
        teacherNameTv.setText(name);
    }

    @Override
    public void answerSuccess() {
        sCall.hangup();//结束通话
        finish();
        EventBus.getDefault().post(new OrderDetailEvent());
        EventBus.getDefault().post(new OrderListEvent());
        IMEventBean callEvent = new IMEventBean();
        callEvent.type = Common.Answer_Success_Event;
        if (orderDetailBean != null) {
            callEvent.orderId = orderDetailBean.getOrderId();
            callEvent.classId = orderDetailBean.getId();
            V2TIMManager.getInstance().sendC2CTextMessage(new Gson().toJson(callEvent), orderDetailBean.getUserId(), callback);
        } else {
            callEvent.orderId = orderId;
            callEvent.classId = classId;
            V2TIMManager.getInstance().sendC2CTextMessage(new Gson().toJson(callEvent), answerUserId, callback);
        }
    }

    @Override
    public void cancelOrderSuccess() {
        if (MainApplication.Identity.equals(Common.NORMAL)) {
            if (sCall == null) {
                finish();
                return;
            }
            sCall.reject();
            finish();
            EventBus.getDefault().post(new OrderDetailEvent());
            EventBus.getDefault().post(new OrderListEvent());
        } else {
            if (sCall == null) {
                finish();
                return;
            }
            sCall.hangup();
            finish();
            EventBus.getDefault().post(new OrderDetailEvent());
            EventBus.getDefault().post(new OrderListEvent());
        }
    }

    @Subscribe
    public void onEvent(CallEvent event) {
        if (event.type == Common.UserEnter) {//进入通话
            mediaPlayer.release();
            if (answerType == 0) {//没有选择解答方式的时候，首次发起语音通话彼此沟通
                if (MainApplication.Identity.equals(Common.ANSWER)) {
                    IMEventBean callEvent = new IMEventBean();
                    callEvent.type = Common.Order_Id_Event;
                    callEvent.orderId = orderDetailBean.getOrderId();
                    callEvent.classId = orderDetailBean.getId();
                    String json = new Gson().toJson(callEvent);
                    V2TIMManager.getInstance().sendC2CTextMessage(json, orderDetailBean.getUserId(), callback);//学生接通后，还未选择解答方式，发送id给学生，让学生选择解答方式。
                } else {
                    videoLl.setVisibility(View.GONE);
                    answerOverBtn.setVisibility(View.GONE);
                    callingCancelBtn.setVisibility(View.GONE);
                    //answerTypeLl.setVisibility(View.VISIBLE);
                }
            } else if (answerType == TYPE_AUDIO_CALL) {//提问人选择了解答方式重新发起语音给解答人
                if (MainApplication.Identity.equals(Common.ANSWER)) {
                    showTimeCount();//计时
                    videoLl.setVisibility(View.GONE);
                    callingCancelBtn.setVisibility(View.GONE);
                    answerTypeLl.setVisibility(View.GONE);
                    answerOverBtn.setVisibility(View.VISIBLE);
                } else {
                    showTimeCount();//计时
                    videoLl.setVisibility(View.GONE);
                    callingCancelBtn.setVisibility(View.GONE);
                    answerTypeLl.setVisibility(View.GONE);
                    answerOverBtn.setVisibility(View.VISIBLE);
                }
            } else if (answerType == TYPE_VIDEO_CALL) {
                showTimeCount();//计时
                if (MainApplication.Identity.equals(Common.ANSWER)) {
                    videoLl.setVisibility(View.GONE);
                    callingCancelBtn.setVisibility(View.GONE);
                    answerTypeLl.setVisibility(View.GONE);
                    answerOverBtn.setVisibility(View.VISIBLE);
                } else {
                    videoLl.setVisibility(View.GONE);
                    callingCancelBtn.setVisibility(View.GONE);
                    answerTypeLl.setVisibility(View.GONE);
                    answerOverBtn.setVisibility(View.VISIBLE);
                }
            }
            isCalling = true;
        } else if (event.type == Common.UserLeave) {//对方挂断
            if (MainApplication.Identity.equals(Common.NORMAL)) {
                if (answerOverBtn.getVisibility() == View.VISIBLE) {//这个按钮显示，证明处于解答中，对方点击了解答完毕
                    ToastUtil.show(this, "问题解答完毕");
                    finish();
                    EventBus.getDefault().post(new OrderDetailEvent());
                    EventBus.getDefault().post(new OrderListEvent());
                } else {
                    ToastUtil.show(this, "对方挂断电话");
                    finish();
                    EventBus.getDefault().post(new OrderDetailEvent());
                    EventBus.getDefault().post(new OrderListEvent());
                }
            } else {
                if (callingCancelBtn.getVisibility() == View.VISIBLE) {
                    callingCancelBtn.setVisibility(View.GONE);
                } else if (answerOverBtn.getVisibility() == View.VISIBLE) {//这个按钮显示，证明处于解答中，对方点击了解答完毕
                    ToastUtil.show(this, "确认了问题解答完毕");
                    finish();
                    EventBus.getDefault().post(new OrderDetailEvent());
                    EventBus.getDefault().post(new OrderListEvent());
                }
            }
        } else if (event.type == Common.Order_Id_Event) {
            orderId = event.orderId;
            classId = event.classId;
            answerTypeLl.setVisibility(View.VISIBLE);
        } else if (event.type == Common.onInvited) {//正常只有解答人才会收到这个
            if (Common.ANSWER.equals(MainApplication.Identity)) {
                answerType = event.callType;
                if (answerType == TYPE_AUDIO_CALL) {
                    sCall.accept();

                } else if (answerType == TYPE_VIDEO_CALL) {//解答人接到视频
                    sCall.setMicMute(false);
                    sCall.setHandsFree(true);
                    headRl.setVisibility(View.GONE);
                    smallTxCloudVideoView.setVisibility(View.VISIBLE);
                    sCall.openCamera(true, smallTxCloudVideoView);
                    sCall.accept();
                }
            }
        } else if (event.type == Common.onCallingCancel) {//有人打电话给你，但是那个人没等你接听就挂断了
            finish();
        } else if (event.type == Common.onReject) {//你打电话给他，他拒绝接听
            mPresenter.cancelOrder(orderDetailBean.getOrderId());
        } else if (event.type == Common.onUserVideoAvailable) {
            boolean isVideoAvailable = event.isVideoAvailable;
            if (isVideoAvailable) {
                //表示对方的视频画面已经拿到，此时可以展示对方的视频影像
                txCloudVideoView.setVisibility(View.VISIBLE);
                sCall.startRemoteView(event.userId, txCloudVideoView);
            } else {
                sCall.stopRemoteView(event.userId);
            }
        } else if (event.type == Common.Join_Room_Event) {//白板进入房间
            Intent intent = new Intent(AnswerActivity.this, WriteBroadActivity.class);
            intent.putExtra(Common.ORDER_ID, orderDetailBean.getOrderId());
            intent.putExtra(Common.ClassId, orderDetailBean.getId());
            intent.putExtra(Common.USER_ID, orderDetailBean.getUserId());
            intent.putExtra(Common.ORDER, orderDetailBean);
            startActivity(intent);
            finish();
        } else if (event.type == Common.onLineBusy) {//忙线中
            if (orderDetailBean == null) {
                cancelOrderSuccess();
            } else {
                mPresenter.cancelOrder(orderDetailBean.getOrderId());
            }
        } else if (event.type == Common.onCallingTimeout) {//超时
            if (answerOverBtn.getVisibility() == View.VISIBLE) {//代码自动接听后，也会有超时返回，腾讯云的问题，加个过滤
                return;
            }
            if (orderDetailBean == null) {
                ToastUtil.show(this, "超时没人接听");
                cancelOrderSuccess();
            } else {
                mPresenter.cancelOrder(orderDetailBean.getOrderId());
                ToastUtil.show(this, "超时没人接听");
            }
        } else if (event.type == Common.onNoResp) {
            if (answerOverBtn.getVisibility() == View.VISIBLE) {//代码自动接听后，也会有超时返回，腾讯云的问题，加个过滤
                return;
            }
            if (orderDetailBean == null) {
                ToastUtil.show(this, "无人应答！");
                cancelOrderSuccess();
            } else {
                ToastUtil.show(this, "无人应答！");
                mPresenter.cancelOrder(orderDetailBean.getOrderId());
            }
        } else if (event.type == Common.onCallEnd) {
            uiHandler.sendEmptyMessageAtTime(1002, 2000);
        } else if (event.type == Common.Answer_Success_Event) {
            if(this.isFinishing()||this.isDestroyed()){
                return;
            }
            sCall.hangup();//结束通话
            ToastUtil.show(this, "对方确认了问题解答完毕");
            finish();
            EventBus.getDefault().post(new OrderDetailEvent());
            EventBus.getDefault().post(new OrderListEvent());
        }
    }

    private void showTimeCount() {
        if (mTimeRunnable != null) {
            return;
        }
        mTimeCount = 0;
        if (mTimeRunnable == null) {
            mTimeRunnable = new Runnable() {
                @Override
                public void run() {
                    mTimeCount++;
                    mTimeHandler.postDelayed(mTimeRunnable, 1000);
                }
            };
        }
        mTimeHandler.postDelayed(mTimeRunnable, 1000);
    }

    private void stopTimeCount() {
        mTimeHandler.removeCallbacks(mTimeRunnable);
        mTimeRunnable = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          /*  sCall.hangup();
            finish();*/
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        stopTimeCount();
        mTimeHandlerThread.quit();
        mediaPlayer.release();
    }
}
